package tech.ezrealc.fall2023.interceptor;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.ezrealc.fall2023.exception.TokenInvalidException;
import tech.ezrealc.fall2023.service.SessionService;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private SessionService sessionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getMethod().equalsIgnoreCase("options")){
            return true;
        }else {
            boolean hasValidToken = sessionService.verifyToken(request.getHeader("Fall2023-Token"));
            if (hasValidToken) {
                return true;
            } else {
                throw new TokenInvalidException("Invalid token");
            }
        }
    }
}
